package com.feixiang.springbootinit.service;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.feixiang.springbootinit.common.Result;
import com.feixiang.springbootinit.wechat.SessionArchive;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
/**
 * 企微存档服务
 */
public class WeChatService {
    @Autowired
    private SessionArchive sessionArchive;

    private String[] msgtypeStr = {"image", "voice", "video", "emotion", "file"};
    private static String priKey =
            "-----BEGIN RSA PRIVATE KEY-----\n" +
                    "MIIEogIBAAKCAQEApTDdP6E4g+IGYP1losxEA+o+3g9TMBUFJvQrse0ZMoG8SAs7\n" +
                    "DIi0c0MmvE3gEBUADySLJ+7svDQrXpC2rU9fIwbwS56zyd79hWcv8usfZb2czkuE\n" +
                    "15EsZwdzv7n33leRBgzvwqOqfA33VN0km5xjXK0IXkwytkhYwkjOo91iegg3Zt0k\n" +
                    "iDWHxHQyy8vZhnbG3wt1u7NzDmaDAYubN7f5NwKLwH8Pxb8IODSxJEQroYmt9GWU\n" +
                    "gER3n8XzlN8lkvTnm6HfOqY+jpVkunKkPlfTWfDd+3aZfv22dhmu7d6Qdza8B+hx\n" +
                    "M9nXmCDbOrjYpElPOKReMZR48dV6/mZEIhzqdQIDAQABAoIBAAvkXqksBBOKfAcT\n" +
                    "dvOnXOYjQO9fjw+RE9PgFB01AnFeYZ2WIWQfm04I8Yrw2EaQHHb6nIH9c1GBN/YQ\n" +
                    "2PXVFvZAk5/+BtdrlDi8WvlT7+i1I8q+KQwTyWyJXs3Yp318NFaJK+GJQsa3gqy7\n" +
                    "Vt1U/to3IrkXJzd0Md+aujWVxHcgbmOGU/pFIzu21KrpM0q4DW169M06dfkuKebN\n" +
                    "6MxRf9wIskur84qZ/QhsWqgB/3DavQOTndyuX05+Qmyl3BNzGiBVDHErcPCtLVQm\n" +
                    "Eb1oMP0O99buEGLEL93UwDNNST72ZkZpjgc0ID6w3JlRb9Pc5cFO3JNybZOXCVXd\n" +
                    "kzmIoEECgYEA7SrKTj3fJeEmI4qwPOZ5dS22GofPO6i6zyHDS0A9UxUBGLBCi0tT\n" +
                    "7yTWOnqXEOFCDFYdb05i6pd0MYaxENo1jfa/2NLXbl7DzE5x2HZ5e9r3Lqa47sGv\n" +
                    "FL4EeAiRuR9RPRRzmC0mstGlw8XGKh9g9mYBeJtHYKtlWcoJuLyWl20CgYEAsk7q\n" +
                    "0erHYRUA/UEBqhX8qPf1oDY13f7k8VpP/BFmPMjhTztOP8EzAz2d47TRfSIMD4hT\n" +
                    "kgZaAmefvAmbUmYZcfu+fy1SVY1bao3k6Ys1kiNHHq27pGZ1qi7FV3Lyhbju3rsI\n" +
                    "9FULE0JZ7EGB3d9EEUvtyEUSw4UFZ15PPvAdEikCgYAt7wyxrLAMcRfm6FSL5wN9\n" +
                    "G3ZamxUa8+oCdgKSD4YREk9dDb5FpjhCZ/sJ5nZdsZMOOpuG1EK6Ns0tTm362phm\n" +
                    "v3SWtPc+jCIV7teD2iZbQ6R+J5JHw8F6HfdVnCtFFHiygMSGo7AMECivyx0/SUaJ\n" +
                    "UmZUipZ/dZKymjvZyMTN3QKBgCoyzxP68lChfehxuAkexvreI/1Ulw8AwgH0k7Ve\n" +
                    "EMoV6Gyt5mjkOkRsEq/PHTz2D9ClPNH0Ot0S1RTVWTL5AtCc+YpzmWax246uIhy7\n" +
                    "W2RIgQ5bo2rW7MXn58A4bfkDuVRxAz9/2O0n6Mwm/KsbqapGQ/H/lt863fqGsU59\n" +
                    "2QNxAoGAQNRqfzU5QEoVhuiqzisb5gisSw21pu79TuPoT1sPh1fD5hVgoaFjZBgw\n" +
                    "Sf7G4R9xDlKmWQzMMpJEjT/7aItoKYHcvyGSYMFC7a8dyIbpW/UXA/bv3P0TTWf8\n" +
                    "ZMI4mNB3h4IhDAC0ooDby6qWTXPQjl15JTKMyPRJ3EGLjPN7zu0=\n" +
                    "-----END RSA PRIVATE KEY-----\n";
    public Result getMsgSave() {
        //初始化sdk
        sessionArchive.initSdk("123", "ww1fa77b8003fe9308", "qA-ZDw0HrPeQWKnH_5F6XGRxj6-Uc79vnznuyT7g8is");
        //获取会话数据,这里我是把seq的值存入了数据库，这里你们自行存库存redis存内存当中都行
        //代表消息的seq值，标识消息的序号。再次拉取需要带上上次回包中最大的seq。
        //String sqlV = tWxSysconfigMapper.getTWxSysconfig(AppConstant.RECORD_SEQ);
        String sqlV = "0";
        int seq = Integer.valueOf(sqlV);
        int limit = 1000;
        List<String> msgTypeList = Arrays.asList(msgtypeStr);
        int a = 1;
        while (true) {
            log.info("******第{}次拉取开始*****", a);
            Result data = sessionArchive.getChatData("123", seq, limit, null, null, 10);
            if (data.getCode() == Result.Type.SUCCESS.value()) {
                //拿到了会话数据，此时还没有解密
                //样例{"errcode":0,"errmsg":"ok","chatdata":[{"seq":196,"msgid":"CAQQ2fbb4QUY0On2rYSAgAMgip/yzgs=","publickey_ver":3,"encrypt_random_key":"ftJ+uz3n/z1DsxlkwxNgE+mL38H42/KCvN8T60gbbtPD+Rta1hKTuQPzUzO6Hzne97MgKs7FfdDxDck/v8cDT6gUVjA2tZ/M7euSD0L66opJ/IUeBtpAtvgVSD5qhlaQjvfKJc/zPMGNK2xCLFYqwmQBZXbNT7uA69Fflm512nZKW/piK2RKdYJhRyvQnA1ISxK097sp9WlEgDg250fM5tgwMjujdzr7ehK6gtVBUFldNSJS7ndtIf6aSBfaLktZgwHZ57ONewWq8GJe7WwQf1hwcDbCh7YMG8nsweEwhDfUz+u8rz9an+0lgrYMZFRHnmzjgmLwrR7B/32Qxqd79A==","encrypt_chat_msg":"898WSfGMnIeytTsea7Rc0WsOocs0bIAerF6de0v2cFwqo9uOxrW9wYe5rCjCHHH5bDrNvLxBE/xOoFfcwOTYX0HQxTJaH0ES9OHDZ61p8gcbfGdJKnq2UU4tAEgGb8H+Q9n8syRXIjaI3KuVCqGIi4QGHFmxWenPFfjF/vRuPd0EpzUNwmqfUxLBWLpGhv+dLnqiEOBW41Zdc0OO0St6E+JeIeHlRZAR+E13Isv9eS09xNbF0qQXWIyNUi+ucLr5VuZnPGXBrSfvwX8f0QebTwpy1tT2zvQiMM2MBugKH6NuMzzuvEsXeD+6+3VRqL"}]}
                JSONObject chatData = JSONUtil.parseObj(data.getData());
                JSONArray jsonArray = chatData.getJSONArray("chatdata");
                if (!jsonArray.isEmpty()) {
                    //遍历
                    for (int i = 0; i < jsonArray.size(); i++) {
                        seq = jsonArray.getJSONObject(i).getInt("seq");
                        //这里记录着seq
                        //TODO 待实现记录seq
                        Map<String, Object> seqMap = JSONUtil.createObj();
                        seqMap.put("seq", seq);
                        JSONObject chatOne = jsonArray.getJSONObject(i);
                        log.info("密钥信息:{}", chatOne.toString());
                        try {
                            //公钥版本号，我这里是到了第四个版本，之前的版本不记得了，所以之前版本的消息都不解密了
//                            if (chatOne.getInt("publickey_ver") != 4) {
//                                continue;
//                            }
                            //解密，pk是放在代码当中的私钥，
                            Result dcRes = sessionArchive.decryptData("123", priKey, chatOne.getStr("encrypt_random_key"), chatOne.getStr("encrypt_chat_msg"));
                            if (dcRes.getCode() == Result.Type.SUCCESS.value()) {
                                log.info("解密数据:{}", dcRes.getData());
                                //解密数据
                                JSONObject res = JSONUtil.parseObj(dcRes.getData());
                                //res就是解密之后的数据，各位可以自行判断消息类型来处理想要的消息
                                res.getStr("msgtype");
                                //文本消息
                                if ("text".equals(res.getStr("msgtype"))) {
                                    System.out.println(res.getJSONObject("text").getStr("content"));
                                } else if (msgTypeList.contains(res.getStr("msgtype"))) {
                                    //处理媒体消息,上面有拉取媒体消息的方法，自行处理
                                    //返回格式待处理
                                    Map<String, Object> map = (Map<String, Object>) sessionArchive.getMediaDataAndUpload("123", res.getStr("msgtype"), res, null, null, 10);
                                    System.out.println(JSONUtil.toJsonStr(map));
                                } else if ("revoke".equals(res.getStr("msgtype"))) {
                                    //撤回消息
                                    System.out.println(res.getJSONObject("revoke").getStr("pre_msgid"));
                                } else if ("agree".equals(res.getStr("msgtype"))) {
                                    //同意会话聊天内容
                                    System.out.println(res.getJSONObject("agree").toString());
                                } else if ("disagree".equals(res.getStr("msgtype"))) {
                                    //不同意消息
                                    System.out.println(res.getJSONObject("disagree").toString());
                                } else if ("card".equals(res.getStr("msgtype"))) {
                                    //名片
                                    System.out.println(res.getJSONObject("card").toString());
                                } else if ("location".equals(res.getStr("msgtype"))) {
                                    //位置
                                    System.out.println(res.getJSONObject("location").toString());
                                } else if ("link".equals(res.getStr("msgtype"))) {
                                    //链接
                                    System.out.println(res.getJSONObject("link").toString());
                                } else if ("weapp".equals(res.getStr("msgtype"))) {
                                    //小程序
                                    System.out.println(res.getJSONObject("weapp").toString());
                                } else if ("chatrecord".equals(res.getStr("msgtype"))) {
                                    //会话记录消息
                                    System.out.println(res.getJSONObject("chatrecord").toString());
                                } else if ("todo".equals(res.getStr("msgtype"))) {
                                    //代办消息
                                    System.out.println(res.getJSONObject("todo").toString());
                                } else if ("vote".equals(res.getStr("msgtype"))) {
                                    //投票消息
                                    System.out.println(res.getJSONObject("vote").toString());
                                } else if ("collect".equals(res.getStr("msgtype"))) {
                                    //填表消息
                                    System.out.println(res.getJSONObject("collect").toString());
                                } else if ("redpacket".equals(res.getStr("msgtype"))) {
                                    //红包消息
                                    System.out.println(res.getJSONObject("redpacket").toString());
                                } else if ("meeting".equals(res.getStr("msgtype"))) {
                                    //会议邀请消息
                                    System.out.println(res.getJSONObject("meeting").toString());
                                } else if ("docmsg".equals(res.getStr("msgtype"))) {
                                    //在线文档消息
                                    System.out.println(res.getJSONObject("doc").toString());
                                } else if ("markdown".equals(res.getStr("msgtype"))) {
                                    //MarkDown格式消息
                                    System.out.println(res.getJSONObject("info").toString());
                                } else if ("news".equals(res.getStr("msgtype"))) {
                                    //图文消息
                                    System.out.println(res.getJSONObject("info").toString());
                                } else if ("calendar".equals(res.getStr("msgtype"))) {
                                    //图文消息
                                    System.out.println(res.getJSONObject("calendar").toString());
                                } else if ("mixed".equals(res.getStr("msgtype"))) {
                                    //混合消息
                                    JSONObject mixed = res.getJSONObject("mixed");
                                    JSONArray jsonArray1 = mixed.getJSONArray("item");
                                    if (!jsonArray1.isEmpty()) {
                                        for (int j = 0; j < jsonArray1.size(); j++) {
                                            JSONObject object = jsonArray1.getJSONObject(j);
                                            if (msgTypeList.contains(object.getStr("type"))) {
                                                //处理媒体消息
                                                JSONObject object1 = JSONUtil.parseObj(object.getStr("content"));
                                                //格式做处理
                                                Map<String, Object> map = (Map<String, Object>) sessionArchive.getMediaDataAndUpload("skid", object.getStr("type"), object1, null, null, 10);
                                                object.set("content", map);
                                                jsonArray1.set(j, object);
                                            }
                                        }
                                    }
                                    mixed.set("item", jsonArray1);
                                    System.out.println(mixed.toString());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //更新SEQ
                    //tWxSysconfigMapper.updateTWxSysconfig(seqMap.get("seq").toString(),AppConstant.RECORD_SEQ);
                } else {
                    //当前消息已拉完
                    break;
                }
            } else {
                break;
            }
            log.info("******第{}次拉取完毕*****", a);
            a++;
        }
        log.info("******会话拉取结束******");
        return Result.success("会话拉取结束");
    }


}

